//
// 嗨~ o(*￣▽￣*)ブ
// Created by Mokou on 2020/9/22.
//

#import "Util.h"
#import "ElecUpgrade.h"
#import "GlobalData.h"


@implementation ElecUpgrade

- (instancetype)init:(NSDictionary *)_data {
    if (self = super.init) {
        if ([Util notNull:_data k:@"box_sn"])
            self.box_sn = _data[@"box_sn"];

        if ([Util notNull:_data k:@"user_id"])
            self.user_id = _data[@"user_id"];

        if ([Util notNull:_data k:@"md5"])
            self.md5 = _data[@"md5"];

        if ([Util notNull:_data k:@"version"])
            self.version = _data[@"version"];

        if ([Util notNull:_data k:@"url"])
            self.url = _data[@"url"];

        if ([Util notNull:_data k:@"local_path"])
            self.local_path = _data[@"local_path"];

    }

    return self;
}

- (NSDictionary *)getDict {
    NSMutableDictionary *res = @{}.mutableCopy;

    if(self.box_sn)
        res[@"box_sn"] = self.box_sn;

    if(self.user_id)
        res[@"user_id"] = self.user_id;

    if(self.md5)
        res[@"md5"] = self.md5;

    if(self.version)
        res[@"version"] = self.version;

    if(self.url)
        res[@"url"] = self.url;

    if(self.local_path)
        res[@"local_path"] = self.local_path;

    return res;
}

+ (NSDictionary *)create:(NSDictionary *)_data {
    NSMutableDictionary *res = @{}.mutableCopy;
    if (![Util notNull:_data k:@"data"]) return [Util callBackJson:@{@"upgrade": res}];
    NSDictionary *data = _data[@"data"];

    if (![Util notNull:data k:@"user_id"]) return [Util callBackJson:@{@"upgrade": res}];
    NSString *userId = data[@"user_id"];

    if (![Util notNull:data k:@"box_sn"]) return [Util callBackJson:@{@"upgrade": res}];
    NSString *boxSn = data[@"box_sn"];

    ElecUpgrade *upgrade = ElecUpgrade.new;
    upgrade.user_id = userId;
    upgrade.box_sn = boxSn;
    Database *db = [GlobalData shareInstance].db;
    [db upgrade_create:upgrade];

    res = upgrade.getDict.mutableCopy;

    return [Util callBackJson:@{@"upgrade": res}];
}

+ (BOOL)clear:(NSDictionary *)_data {
    if (![Util notNull:_data k:@"data"]) return NO;
    NSDictionary *data = _data[@"data"];

    if (![Util notNull:data k:@"user_id"]) return NO;
    NSString *userId = data[@"user_id"];

    Database *db = [GlobalData shareInstance].db;
    [db upgrade_clear:userId];
    return YES;
}

+ (BOOL)delete:(NSDictionary *)_data {
    if (![Util notNull:_data k:@"data"]) return NO;
    NSDictionary *data = _data[@"data"];

    if (![Util notNull:data k:@"user_id"]) return NO;
    NSString *userId = data[@"user_id"];

    if (![Util notNull:data k:@"box_sn"]) return NO;
    NSString *boxSn = data[@"box_sn"];

    Database *db = [GlobalData shareInstance].db;
    [db upgrade_delete:userId boxSn:boxSn];
    return YES;
}

+ (NSDictionary *)download:(NSDictionary *)_data {
    NSMutableDictionary *res = @{}.mutableCopy;
    if (![Util notNull:_data k:@"data"]) return [Util callBackJson:@{@"upgrade": res}];
    NSDictionary *data = _data[@"data"];

    if (![Util notNull:data k:@"user_id"]) return [Util callBackJson:@{@"upgrade": res}];
    NSString *userId = data[@"user_id"];

    if (![Util notNull:data k:@"box_sn"]) return [Util callBackJson:@{@"upgrade": res}];
    NSString *boxSn = data[@"box_sn"];

    if (![Util notNull:data k:@"cache_file"]) return [Util callBackJson:@{@"upgrade": res}];
    NSString *cacheFile = data[@"cache_file"];

    NSDictionary *moveRes = [[GlobalData shareInstance].fileSelector moveUpgradeCacheToLocal:cacheFile];
    NSString *localFilePath = moveRes[@"path"];
    NSString *md5 = moveRes[@"md5"];

    if (!localFilePath) return [Util callBackJson:@{@"upgrade": res}];

    Database *db = [GlobalData shareInstance].db;
    [db upgrade_download:userId boxSn:boxSn localFilePath:localFilePath md5:md5];

    ElecUpgrade *upgrade = [db upgrade_select:boxSn userId:userId];

    res = upgrade.getDict.mutableCopy;

    return [Util callBackJson:@{@"upgrade": res}];
}

+ (NSDictionary *)update:(NSDictionary *)_data {
    NSMutableDictionary *res = @{}.mutableCopy;
    if (![Util notNull:_data k:@"data"]) return [Util callBackJson:@{@"upgrade": res}];
    NSDictionary *data = _data[@"data"];

    if (![Util notNull:data k:@"user_id"]) return [Util callBackJson:@{@"upgrade": res}];
    NSString *userId = data[@"user_id"];

    if (![Util notNull:data k:@"box_sn"]) return [Util callBackJson:@{@"upgrade": res}];
    NSString *boxSn = data[@"box_sn"];

    NSString *md5 = nil;
    if ([Util notNull:data k:@"md5"])
        md5 = data[@"md5"];

    NSString *version = nil;
    if ([Util notNull:data k:@"version"])
        version = data[@"version"];

    NSString *url = nil;
    if ([Util notNull:data k:@"url"])
        url = data[@"url"];

    Database *db = [GlobalData shareInstance].db;
    ElecUpgrade *upgrade = [db upgrade_select:boxSn userId:userId];

    // boxSn userId 不存在 或 存在且md5未发生变化
    if (!upgrade || (upgrade.md5 && [upgrade.md5 isEqualToString:md5])) return [Util callBackJson:@{@"upgrade": upgrade.getDict}];

    FileSelector *fs = [GlobalData shareInstance].fileSelector;

    // 检查新MD5文件是否存在
    NSString *existMd5Path = [fs checkUpgradeMd5Exist:md5];
    if (existMd5Path) {
        NSString *old_local_path = upgrade.local_path;

        // 新MD5存在 判断旧文件是否有复用  没有则删除旧文件
        NSArray *sameLocalPath = [db upgrade_select_by_local_path:old_local_path];
        if (sameLocalPath.count <= 1) [fs deleteFile:upgrade.local_path];

        // 保存新文件路径
        upgrade.local_path = existMd5Path;
    } else {
        upgrade.local_path = nil;
    }

    // 保存MD5
    upgrade.md5 = md5;

    // 保存新版本号 及 下载地址
    upgrade.version = version;
    upgrade.url = url;

    // 更新数据库
    [db upgrade_update:upgrade];

    // 返回更新之后的upgradeJson对象
    res = upgrade.getDict.mutableCopy;

    return [Util callBackJson:@{@"upgrade": res}];
}

+ (NSString *)get_cache_file {
    return [[GlobalData shareInstance].fileSelector getNewUpgradeFileCachePath];
}

+ (void)delete_cache_file:(NSString *)cachePath {
    [[GlobalData shareInstance].fileSelector deleteFile:cachePath];
}

+ (NSDictionary *)device_upgrade_query:(NSDictionary *)_data {
    if (![Util notNull:_data k:@"data"]) return [Util callBackJson:@{@"info": @[]}];
    NSDictionary *data = _data[@"data"];

    if (![Util notNull:data k:@"user_id"]) return [Util callBackJson:@{@"info": @[]}];
    NSString *userId = data[@"user_id"];

    Database *db = [GlobalData shareInstance].db;

    NSArray *upgradeArr = [db upgrade_select_by_userId:userId];

    NSMutableArray *resArr_device =@[].mutableCopy;
    NSMutableArray *resArr_upgrade =@[].mutableCopy;

    for (NSDictionary *upgradeData in upgradeArr) {
        ElecUpgrade *upgrade = [[ElecUpgrade alloc] init:upgradeData];
        ElecDevice *device = [db device_select_by_boxSn:upgrade.box_sn];
        if (device) {
            [resArr_device addObject:device.getDict];
            [resArr_upgrade addObject:upgrade.getDict];
        }
    }

    return [Util callBackJson:@{@"device": resArr_device, @"upgrade": resArr_upgrade}];
}

@end
